package com.tjetc.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 演示文件的上传和下载
 *
 * @author gaoyongxiang
 * @version v1.0
 * @date 2025/9/5
 */
@Controller
@RequestMapping("/file/")
public class _9FileController {


    // 实现下载
    @RequestMapping("download")
    public ResponseEntity<byte[]> f(HttpServletRequest request) throws IOException {
        // 1. 先获取文件下载的输入流 拿到下载的资源路径
        InputStream in = request.getServletContext().getResourceAsStream("/resource/1.jpg");
//        System.out.println(in.available());
        // 2.创建返回的字节数组 用来保存我要给客户端的二进制数据
        // in.available() 这个就是图片大小
        byte[] bytes = new byte[in.available()];
        // 3. 将图片输入保存到字节数组中
        in.read(bytes);
        // 4. 返回数据
        // 我们需要一个响应头信息 因为下载图片的响应头 是比较特殊的
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=1.jpg");
        ResponseEntity<byte[]> response = new ResponseEntity<>(bytes, headers, HttpStatusCode.valueOf(200));
        return response;
    }


    // 实现上传
    @RequestMapping("upload")
    public String f1(
            @RequestParam("file") MultipartFile file,
            @RequestParam("fileName") String fileName,
            HttpServletRequest request
    ) throws IOException {
        // 1. 拿到文件名称
        String originalFilename = file.getOriginalFilename();
//        System.out.println(originalFilename);
//        System.out.println(fileName);
        // 2. 创建要保存的路径
        String path = request.getServletContext().getRealPath("/resource/" + originalFilename);
        // 3. 根据路径创建文件
        File file1 = new File(path);
        // 4. 上传文件
        file.transferTo(file1);
        return "ok";
    }


}